<template>
	<div style="width: 100%;">
		<div style="display: flex; flex-direction: column; align-items: center; width: 90%;margin: 0 auto;">
			<div style="background-color: #5b5b5b;width: 100%;border-radius: 10px;">
				<div class="wd" style="padding-bottom: 70px;height: 60vh;width: 100%;overflow: scroll;" id="chat-wrap"
					ref="mianscroll">
					<div :class="data.type === 'admin' ? 'service-admin' : 'service-user'"
						v-for="(data, index) in chatList" :key="index" style="margin-top: 20px; display: flex;">
						<div>
							<img style="height: 30px; width: 30px;background-color: white;border-radius: 100%;margin-left: 10px;"
								src="../../assets/service/service.png" v-if="data.type === 'admin'"></img>
							<img style="height: 30px; width: 30px;background-color: white;border-radius: 100%;margin-right: 10px;"
								src="@/assets/service/user.png" v-else></img>

						</div>
						<div style="word-break:break-all; word-wrap:break-word; margin: 0px 10px;max-width: 50vw;"
							class="chat-item-content" v-if="data.type === 'admin'">
							{{data.text}}
						</div>
						<div style="word-break:break-all; word-wrap:break-word; margin: 0px 10px; max-width: 50vw;"
							class="chat-item-content" v-else>
							{{data.text}}
						</div>
					</div>
				</div>
			</div>

			<div style="width: 100%; background-color: #171717;">
				<div style=" background-color: #171717; width:100%;position: relative;">
					<div class="wd"
						style="display: flex; justify-content: space-between; padding-top: 5px; height: 15.5vh; bottom: 10px;">
						<textarea fixed maxlength="-1"
							style="width: 100%; max-height: 15vh;min-height: 15vh;font-size: 20px;border-radius: 10px;border: 1px solid white;"
							v-model="send_msg"></textarea>

						<el-button
							style="letter-spacing: 5px; color: white; background: #0676ff;;border-radius: 5px; margin-left: 15px; width: 6vw;height: 40px;  text-align: center;position: absolute;right: 1vw;bottom: 0;"
							@click="sendMsg">发送</el-button>
					</div>
				</div>
			</div>
		</div>
	</div>

</template>

<script>
	// 定义聊天类
	function Chat(type = 'user', text = '') {
		this.type = type
		this.text = text
	}

	function SocketMessage(from = '', to = '', message = '') {
		this.from = from
		this.to = to
		this.message = message
	}


	// 更新聊天缓存
	function saveChatList(chatList) {
		const str = JSON.stringify(chatList)
		// uni.setStorage({
		//     key: 'chatList',
		//     data: JSON.stringify(chatList)
		// })
		localStorage.setItem("chatList", JSON.stringify(chatList))
	}

	import {
		getOnlineAdminId
	} from '../../api/work.js'
	export default {
		name: "userchat",
		data() {
			return {
				text: '',
				chatList: [],
				to: '',
				scollHeight: 0,
				scrollTop: 0,
				scrollTopOld: 0,
				bottomHeight: 0,


				path: "ws://45.145.75.2:8102/api/websocket/",
				receive_msg: '',
				send_msg: '',
				readyState: '连接未开启',


				userID: 1111111127
			}
		},
		methods: {
			topScrollClick() {
				this.$nextTick(() => {
					let scrollEl = this.$refs.mianscroll;
					scrollEl.scrollTo({
						top: scrollEl.scrollHeight,
						behavior: 'smooth'
					});
				});
			},
			getTo() {
				getOnlineAdminId().then(res => {
					console.log(res)
					if (res.code !== 200) {
						this.chatList = [...this.chatList, new Chat('admin', '暂无客服在线，请稍后在试')]
						this.toBottom()
						return
					}
					this.to = res.data
				})
			},
			initWebsocket() {


				this.socket = new WebSocket(this.path + this.userID);
				// 用于指定连接成功后的回调函数
				this.socket.onopen = this.onopen
				// 用于指定连接关闭后的回调函数
				this.socket.onclose = this.onclose
				// 用于指定连接失败后的回调函数
				this.socket.onerror = this.onerror
				// 用于指定当从服务器接受到信息时的回调函数
				this.socket.onmessage = this.onmessage



				try {
					this.chatList = JSON.parse(localStorage.getItem('chatList'))
					if (!this.chatList) {
						saveChatList([])
					}
				} catch {
					this.chatList = []
				}
				// uni.showLoading({
				//     title: '连接客服中',
				//     mask: true
				// })


				this.$message.info("连接客服中")
				// const socketTask = uni.connectSocket({
				//     url: BASE_URL.replace("http", "ws") + '/api/websocket/' + getUserId(),
				//     complete: () => {},
				//     header: {
				//         token: getToken()
				//     }
				// })


				// this.socket = new WebSocket(()=>{
				//     console.log('连接成功！')
				//     this.$message.success("连接成功")
				//     // uni.hideLoading()
				//     // uni.showToast({
				//     //     title: '连接成功',
				//     //     icon: 'success',
				//     //     duration: 1000
				//     // })
				// })


				// uni.onSocketOpen(() => {
				//     console.log('连接成功！')
				//     uni.hideLoading()
				//     uni.showToast({
				//         title: '连接成功',
				//         icon: 'success',
				//         duration: 1000
				//     })
				// })

				// uni.onSocketError(() => {
				//     console.log('连接失败')
				//     uni.hideLoading()
				//     uni.showToast({
				//         title: '连接失败',
				//         icon: 'error',
				//         duration: 1000
				//     })
				// })

				// 接收服务器回来的参数
				// uni.onSocketMessage((res) => {
				//     const text = JSON.parse(res.data).message
				//     this.chatList = [...this.chatList, new Chat('admin', text)]
				//     saveChatList(this.chatList)
				//     this.toBottom()
				// })
			},
			onopen(event) {
				this.readyState = '连接状态：' + this.connectState(this.socket.readyState);
				console.log('连接开启:', event)
				this.$message({
					showClose: true,
					message: '连接开启',
					type: 'success'
				});
			},
			onclose(event) {
				this.readyState = '连接状态：' + this.connectState(this.socket.readyState);
				console.log('连接关闭:', event)
				this.$message({
					showClose: true,
					message: '连接关闭',
					type: 'success'
				});
			},
			onerror(err) {
				//服务端未启动时，会进入连接出错，其后进入连接关闭
				this.readyState = '连接状态：' + this.connectState(this.socket.readyState);
				console.log('连接出错:', err)
				this.$message({
					showClose: true,
					message: '连接出错',
					type: 'error'
				});
			},
			onmessage(res) {
				this.readyState = '连接状态：' + this.connectState(this.socket.readyState);
				console.log('接收到的消息：', res)
				// this.receive_msg = msg.data
				const text = JSON.parse(res.data).message
				this.chatList = [...this.chatList, new Chat('admin', text)]
				saveChatList(this.chatList)
				// this.toBottom()
				this.topScrollClick()
			},
			openSocket() {
				this.init()
			},
			closeSocket() {
				if (this.socket == null) {
					console.log('连接未开启')
					this.$message({
						showClose: true,
						message: '连接未开启',
						type: 'error'
					});
					return
				}
				this.socket.close(1000, '手动关闭连接')
			},
			sendMsg() {
				if (this.to === '') {
					this.getTo()
					return
				}
				if (this.socket == null) {
					console.log('连接未开启')
					this.$message({
						showClose: true,
						message: '连接未开启',
						type: 'error'
					});
					return
				}
				if (this.socket.readyState != 1) {
					console.log('连接未开启')
					this.$message({
						showClose: true,
						message: '连接未开启',
						type: 'error'
					});
					return
				}


				// if(this.to === '') {
				//     this.getTo()
				//     return
				// }
				if (this.send_msg === '') {
					return
				}
				console.log(this.send_msg)
				const data = new Chat('user', this.send_msg)
				this.chatList = [...this.chatList, data]
				const socketObj = new SocketMessage(this.userID, this.to, this.send_msg)
				// uni.sendSocketMessage({
				//     data: JSON.stringify(socketObj)
				// })


				this.socket.send(JSON.stringify(socketObj))
				saveChatList(this.chatList)
				this.topScrollClick()

			},
			connectState(readyState) {
				switch (readyState) {
					case 0:
						return '正在链接中'
						break;
					case 1:
						return '已经链接并且可以通讯'
						break;
					case 2:
						return '连接正在关闭'
						break;
					case 3:
						return '连接已关闭或者没有链接成功'
						break;
					default:
						return '连接未开启'
						break;
				}
			},
			waitForSocketConnection(socket, callback) {
				setTimeout(() => {
					if (socket.readyState === 1) {
						console.log("连接开启")
						this.$message({
							showClose: true,
							message: '连接开启',
							type: 'success'
						});
						if (callback != null) {
							callback();
						}
						return;

					} else {
						console.log("连接失败，正在重连...")
						this.$message({
							showClose: true,
							message: '连接失败，正在重连……',
							type: 'error'
						});
						waitForSocketConnection(socket, callback);
					}
				}, 5); // wait 5 milisecond for the connection...
			},
		},
		mounted() {
			this.getTo()
			this.initWebsocket()
		}
	}
</script>

<style scoped>
	.service-user {
		flex-direction: row-reverse;
	}

	.service-admin {}

	.service-admin .chat-item-content {
		background-color: white;
	}

	.service-user .chat-item-content {
		background-color: white;
	}

	.chat-item-content {
		padding: 5px 10px;
		border-radius: 5px;
	}
</style>